//
//  WcXyz.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/10/25.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "WcXyz.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_ReqDataGenerator.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK_Enum.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_JsonUtil.h"
#import "OpenSDK_StatisticsManager.h"
#import "OpenSDK_PayManager.h"

//#import "WXApi.h"
#import "WCMApi.h"


//@interface WcXyz() <WXApiDelegate>
@interface WcXyz() <WCMApiDelegate>
@end

@implementation WcXyz

{
    //当前的订单信息
    OpenSDK_PayResData *curPayInfo;
}

static NSString *APP_CONFIG=@"WcAppId";

#pragma mark - OpenSDK_SdkProtrol声明方法
-(void) initInfo {
    [OpenSDK_EventManager addObsver:self selector:@selector(initSDK:) name:OPENSDK_EVENT_INIT object:nil className:@"WcXyz"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_handleOpenURL:) name:OPENSDK_EVENT_APPLICATION_HANDLEOPENURL object:nil className:@"WcXyz"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_options:) name:OPENSDK_EVENT_APPLICATION_OPENURL_OPTIONS object:nil className:@"WcXyz"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_sourceApplication_annotation:) name:OPENSDK_EVENT_APPLICATION_OPENURL_SOURCEAPPLICATION_ANNOTATION object:nil className:@"WcXyz"];
}

#pragma mark - OpenSDK_SdkProtrol声明方法 - 服务器唯一标识
-(NSString *) getServerName {
    return @"WeChat";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 展示的图标
-(NSString *) getDisplayIcon {
    return @"op_pay_wechat.png";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 展示的名字
-(NSString *) getDisplayName {
    return @"微信支付";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 支付平台名
-(NSString *) getPlatform {
    return @"WeChat";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 支付平台版本号
-(NSString *) getPlatformVersion {
    return @"1.0";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 统计的类型名
-(NSString *) getStatisticsType {
    return @"WECHAT";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 调起第三方平台支付，传入opensdk订单号
-(void) startPay:(OpenSDK_PayResData *) opensdkOrder {
    //订单
    curPayInfo = opensdkOrder;
    //服务器端返回的支付调用参数
    NSDictionary *orderExtra = [opensdkOrder.content objectForKey:@"extra"];
    NSLog(@"wechat extra:%@", orderExtra);
    
    //调起微信支付
    dispatch_async(dispatch_get_main_queue(), ^{
        PayReq* req             = [[PayReq alloc] init];
        req.partnerId           = [orderExtra objectForKey:@"partnerid"];
        req.prepayId            = [orderExtra objectForKey:@"prepayid"];
        req.nonceStr            = [orderExtra objectForKey:@"noncestr"];
        req.timeStamp           = [[orderExtra objectForKey:@"timestamp"] intValue];
        req.package             = [orderExtra objectForKey:@"package"];
        req.sign                = [orderExtra objectForKey:@"sign"];
        NSLog(@"wcxyz: npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign);
        [WCMApi sendReq:req completion:^(BOOL success) {
            
        }];
    });
}

-(void) initSDK:(NSNotification*) notification {
    // 微信appId
    NSString *appId = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:APP_CONFIG];
        NSString *universalLinks = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:OpenSDK_UNIVERSAL_LINKS];
//    [WXApi registerApp:appId];
    [WCMApi registerApp:appId universalLink:universalLinks];
}

#pragma mark - 微信回调需要添加的代码，在系统生命周期回调函数
-(void) application_handleOpenURL:(NSNotification*) notification {
    if (curPayInfo == nil) {
        return;// 说明该sdk没有调起支付
    }
    NSLog(@"wcxyz:application_handleOpenURL");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [WCMApi handleOpenURL:url delegate:self];
}

#pragma mark - 微信回调需要添加的代码，在系统生命周期回调函数
-(void) application_openURL_sourceApplication_annotation:(NSNotification*) notification {
    if (curPayInfo == nil) {
        return;// 说明该sdk没有调起支付
    }
    NSLog(@"wcxyz:application_openURL_sourceApplication_annotation");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [WCMApi handleOpenURL:url delegate:self];
}


#pragma mark - 微信回调需要添加的代码，在系统生命周期回调函数
// NOTE: 9.0以后使用新API接口
-(void) application_openURL_options:(NSNotification*) notification {
    if (curPayInfo == nil) {
        return;// 说明该sdk没有调起支付
    }
    NSLog(@"wcxyz:application_openURL_options");
    NSURL *url = [[notification object] objectForKey:OpenSDK_E_OPENURL];
    [WCMApi handleOpenURL:url delegate:self];
}


#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去服务器端查询
        switch (resp.errCode) {
            case WXSuccess:
                NSLog(@"wcxyz:支付成功－PaySuccess，retcode = %d", resp.errCode);
                // 统计渠道支付成功
                [[OpenSDK_StatisticsManager getInstance] collectPaySuccessWithType:OPENSDK_STATS_PAY_SUB_SUCCESS orderId:[curPayInfo getOrderID] cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType]];
                [self checkOrder];
                break;
            case WXErrCodeUserCancel:
                NSLog(@"wcxyz:支付取消");
                // 统计渠道支付取消
                [[OpenSDK_StatisticsManager getInstance] collectPayCancelWithCpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType]];
                // 回调游戏支付取消
                curPayInfo = nil;
                [[OpenSDK_PayManager getInstance] callbackPayCancel];
                break;
            default:
                NSLog(@"wcxyz:支付失败，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                // 统计渠道支付失败
                [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_PAY_SUB_FAIL orderId:nil cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType] failInfo:[NSString stringWithFormat:@"微信支付失败,错误码=%d,错误信息=%@", resp.errCode, resp.errStr]];
                // 回调游戏支付失败
                curPayInfo = nil;
                [[OpenSDK_PayManager getInstance] callbackPayFail:[NSString stringWithFormat:@"微信支付失败(%@)", resp.errStr] withOrder:nil];
                break;
        }
    }
}

- (void) checkOrder {
    NSMutableDictionary *localInfo=[OpenSDK_ReqDataGenerator generateInitDataWithInfo];
    [localInfo setObject:[curPayInfo getUID] forKey:OpenSDK_S_UID];
    [localInfo setObject:[self getPlatform] forKey:OpenSDK_S_PLATFORM];
    [localInfo setObject:[self getPlatformVersion] forKey:OpenSDK_S_PLATFORM_VERSION];
    NSString *localInfoStr = [OpenSDK_ReqDataGenerator generateDataByDictionary:localInfo];
    [self checkOrderWithData:localInfoStr orderID:[curPayInfo getOrderID] httpDelegate:^(OpenSDK_BaseResData *resData) {
        if ([resData isOk]) {
            OpenSDK_PayResData *payInfo=[[OpenSDK_PayResData alloc] initWithData:[resData content]];
            if ([[payInfo getPayStatus] isEqualToString:@"SUCCESS"]) {
                // 统计checkOrder成功
                [[OpenSDK_StatisticsManager getInstance] collectPaySuccessWithType:OPENSDK_STATS_PAY_SUB_CHECK_SUCCESS orderId:[curPayInfo getOrderID] cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType]];
                // 回调外部支付成功
                curPayInfo = nil;
                OpenSDK_OrderInfo *userOrderInfo=[payInfo toUserOrderInfo];
                [[OpenSDK_PayManager getInstance] callbackPaySuccess:nil withOrder:userOrderInfo];
            } else if ([[payInfo getPayStatus] isEqualToString:@"FAIL"]) {
                // 统计checkOrder失败
                [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_PAY_SUB_CHECK_FAIL orderId:nil cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType] failInfo:@"Order status is FAIL"];
                // 回调外部支付失败
                curPayInfo = nil;
                [[OpenSDK_PayManager getInstance] callbackPayFail:@"订单支付失败" withOrder:nil];
            } else {
                // 统计checkOrder为PAY_WAIT_CHECK状态
                [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_PAY_SUB_CHECK_FAIL orderId:nil cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType] failInfo:@"Order status is NEW"];
                // CheckOrder是NeW状态，则回调外部OpenSDK_PAY_WAIT_CHECK
                curPayInfo = nil;
                OpenSDK_OrderInfo *userOrderInfo=[payInfo toUserOrderInfo];
                [[OpenSDK_PayManager getInstance] callbackPayWaitCheck:userOrderInfo];
            }
        } else {
            // 统计checkOrder网络失败
            [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_PAY_SUB_CHECK_FAIL orderId:nil cpOrderId:[curPayInfo getAppData] detail:[self getStatisticsType] failInfo:[resData errorMsg]];
            // 回调外部
            curPayInfo = nil;
            [[OpenSDK_PayManager getInstance] callbackPayFail:[resData errorMsg] withOrder:nil];
        }
        NSLog(@"wcxyz:++++++++++++++++++++++++++++++订单处理结束");
    }];
}

@end
